package com.study.servlet.session.prac02;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.study.servlet.session.prac02.domain.Book;

/**
* @Name: ShowAllBooks
* @Description: Session应用：实现购物车
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-3-3 下午3:52:02 
* @Version: V1.0
 */
public class ShowAllBooks extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8") ;
		PrintWriter out = response.getWriter() ;
		//显示所有的书籍信息
		out.write("本书店有如下奇葩数据：<br/>") ;
		Map<String, Book> books = BookDB.getAllBooks() ;
		for(Map.Entry<String, Book> entry : books.entrySet()) {
			Book book = entry.getValue() ;
			//防止客户端禁用Cookie，重写URL
			String buyBookUrl = request.getContextPath() + "/servlet/BuyBook?id=" + book.getId() ;
			String url = response.encodeURL(buyBookUrl) ;
			out.write(book.getName() + "&nbsp;&nbsp;" +
					"<a href="+ url +">购买书籍</a>") ;
		}
		//重写url
		String showCartUrl = request.getContextPath() + "/servlet/ShowCart" ;
		String url = response.encodeURL(showCartUrl) ;
		out.write("<a href="+ url +">显示购物车</a>") ;
		out.close() ;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
